package com.xyrl.third.aliyun.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xyrl.common.util.ObjectUtil;
import com.xyrl.third.aliyun.config.AliYunProperties;
import com.xyrl.third.aliyun.exception.AliYunException;
import com.xyrl.third.aliyun.vo.AliYunResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * 阿里云短信工具类
 *
 * @author zhongp
 * @version 1.0
 * @className MsgService
 * @company 星纭融链科技服务有限公司
 * @date 2020-01-02 16:52:25
 * @Description
 */
@Slf4j
public class MsgService {
    /**
     * 注入属性配置类
     */
    @Autowired
    AliYunProperties aliYunProperties;

    /**
     * 发送短信
     *
     * @param sendMsgMaps
     * @return
     * @decription https://api.aliyun.com/?spm=a2c4g.11186623.2.13.60d150a4h2sKGt#/?product=Dysmsapi&version=2017-05-25&api=SendSms&tab=DEMO&lang=JAVA
     */
    public AliYunResponse sendMsg(Map<String, String> sendMsgMaps) throws AliYunException {
        DefaultProfile profile = DefaultProfile.getProfile(aliYunProperties.getRegionId(), aliYunProperties.getAccessKeyId(), aliYunProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        //发送短信地址
        request.setSysDomain("dysmsapi.aliyuncs.com");
        //当天日期  发送版本
        request.setSysVersion(aliYunProperties.getMsg().getVersion());
        //请求类型 （发送短信）
        request.setSysAction("SendSms");
        //默认
        request.putQueryParameter("RegionId", aliYunProperties.getRegionId());
        //短信签名
        request.putQueryParameter("SignName", aliYunProperties.getMsg().getSignName());
        for (String key : sendMsgMaps.keySet()) {
            request.putQueryParameter(key, sendMsgMaps.get(key));
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("短信发送返回值:[{}]", response.getData());
            if (ObjectUtil.isNotEmpty(response.getData())) {
                AliYunResponse aliYunResponse = JSONObject.parseObject(response.getData(), AliYunResponse.class);
                return aliYunResponse;
            }
            throw new AliYunException("短信发送异常");
        } catch (ServerException e) {
            log.error("短信发送异常", e);
            throw new AliYunException(e.getMessage());
        } catch (ClientException e) {
            log.error("短信发送异常", e);
            throw new AliYunException(e.getMessage());
        }
    }
}
